<?php


namespace app\controller\admin;

use app\model\AdminAuthGroupAccess;
use app\model\AdminSchool;
use app\model\AdminUser;
use app\util\ReturnCode;
use app\util\Tools;
use think\facade\Request;
use think\Response;

class School extends Base
{
    public function index(): Response {
        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $keywords = $this->request->get('name', '');
        $sortKey = $this->request->get('sortKey', 'create_time');
        $order = $this->request->get('order', 'DESC');

        $obj = (new AdminSchool())->where('is_delete', 0);
        if ($keywords) {
            $obj = $obj->whereLike('name', "%{$keywords}%");
        }
        $listObj = $obj->order($sortKey, $order)
            ->paginate(['page' => $start, 'list_rows' => $limit])->toArray();

        return $this->buildSuccess([
            'list'  => $listObj['data'],
            'count' => $listObj['total']
        ]);
    }

    public function add(): Response {
        $insert = input('post.');
        $insert['password'] = Tools::userMd5($insert['password']);
        $school = AdminSchool::create($insert);
        if ($school === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR);
        }

        return $this->buildSuccess();
    }

    public function edit(): Response {
        $insert = input('post.');
        if ($insert['password'] === '') {
            unset($insert['password']);
        } else {
            $insert['password'] = Tools::userMd5($insert['password']);
        }
        $origin = AdminSchool::find($insert['id'])->toArray();
        $school = AdminSchool::update($insert);
        if ($school === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR);
        }
        // 同步修改账号
        if ($origin['account'] != $school->account
            || $origin['password'] != $school->password
        ) {
            $user = AdminUser::where('school_id',$school->id)
                ->where('username', $origin['account'])
                ->find();
            $is_new = false;
            if (!$user) {
                $user = new AdminUser();
                $user->create_ip = sprintf("%u", ip2long(Request::ip()));
                $is_new = true;
            }
            $user->username = $school->account;
            $user->nickname = $school->name;
            if ($school->password) {
                $user->password = $school->password;
            }
            $user->school_id = $school->id;
            $user->status = 1;
            $user->save();
            if ($is_new) {
                AdminAuthGroupAccess::create([
                    'uid'      => $user->id,
                    'group_id' => '1'
                ]);
            } else {
                AdminAuthGroupAccess::update([
                    'group_id' => '1'
                ], [
                    'uid'      => $user->id
                ]);
            }
        }
        return $this->buildSuccess();
    }

    public function del(): Response {
        $id = $this->request->get('id');
        if (!$id) {
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }

        $school = (new AdminSchool())->where('id', $id)->find();
        $school->is_delete = 1;
        $school->save();

        $user = AdminUser::where('username', $school->account)->where('school_id', $school->id)->find();
        if ($user) {
            AdminAuthGroupAccess::destroy(['uid' => $user->id]);
            $user->delete();
        }

        return $this->buildSuccess();
    }
}